<template>
  <view>
    <!-- 报名未开始 -->
    <TButton
      v-if="
        item.activityStatus === ActivityStatusEnum.REGISTRATION_NOTSTARTED ||
        item.activityStatus === ActivityStatusEnum.REGISTRATION_UNPLAYED
      "
      text="报名未开始"
      type="primary"
      disabled
      custom-class="h-30 linh-30 br-30 px-24"
      :custom-style="{ minWidth: '200rpx' }"
    />
    <!-- 报名进行中 -->
    <template v-else-if="item.activityStatus === ActivityStatusEnum.REGISTRATION_UNDERWAY">
      <template v-if="!item.enrollRestrict || item.maxNum >= item.passedNum">
        <TButtonGroup :position="'unset'" :styles="{ padding: 0 }">
          <!-- 代报名 -->
          <template
            v-if="
              !item.register?.approvalStatus ||
              item.register?.approvalStatus === ApprovalStatusEnum.REJECT
            "
          >
            <!-- 会员报名 -->
            <TButton
              v-if="currentCocId"
              text="立即报名"
              type="primary"
              class="gutter-btn"
              custom-class="h-30 linh-30 br-30 px-24"
              @click.stop="toSignUp('member')"
            />

            <!-- 非会员报名 -->
            <TButton
              v-else
              text="立即报名"
              type="primary"
              class="gutter-btn"
              custom-class="h-30 linh-30 br-30 px-24"
              :custom-style="{ minWidth: '200rpx' }"
              @click.stop="toSignUp('nonmember')"
            />
          </template>

          <TButton
            v-else-if="item.register?.approvalStatus === ApprovalStatusEnum.UNDERREVIEW"
            text="审核中"
            type="primary"
            disabled
            custom-class="h-30 linh-30 br-30 px-24"
            :custom-style="{ minWidth: '200rpx' }"
          />
          <TButton
            v-else-if="item.register?.approvalStatus === ApprovalStatusEnum.NOTPASS"
            text="未通过"
            type="primary"
            disabled
            custom-class="h-30 linh-30 br-30 px-24"
            :custom-style="{ minWidth: '200rpx' }"
          />
          <template v-else-if="item.register?.approvalStatus === ApprovalStatusEnum.PASSED">
            <TButton
              text="等待开始"
              type="primary"
              disabled
              custom-class="h-30 linh-30 br-30 px-24"
              :custom-style="{ minWidth: '200rpx' }"
            />
          </template>
        </TButtonGroup>
      </template>
      <TButton
        v-else
        text="报名人数已满"
        type="primary"
        disabled
        custom-class="h-30 linh-30 br-30 px-24"
        :custom-style="{ minWidth: '200rpx' }"
      />
    </template>
    <!-- 报名结束 -->
    <template v-else-if="item.activityStatus === ActivityStatusEnum.REGISTRATION_END">
      <TButton
        v-if="
          !item.register?.approvalStatus ||
          item.register?.approvalStatus === ApprovalStatusEnum.REJECT
        "
        text="报名已结束"
        type="primary"
        disabled
        custom-class="h-30 linh-30 br-30 px-24"
        :custom-style="{ minWidth: '200rpx' }"
      />
      <TButton
        v-else-if="item.register?.approvalStatus === ApprovalStatusEnum.UNDERREVIEW"
        text="审核中"
        type="primary"
        disabled
        custom-class="h-30 linh-30 br-30 px-24"
        :custom-style="{ minWidth: '200rpx' }"
      />
      <TButton
        v-else-if="item.register?.approvalStatus === ApprovalStatusEnum.NOTPASS"
        text="未通过"
        type="primary"
        disabled
        custom-class="h-30 linh-30 br-30 px-24"
        :custom-style="{ minWidth: '200rpx' }"
      />
      <template v-else-if="item.register?.approvalStatus === ApprovalStatusEnum.PASSED">
        <TButton
          text="等待开始"
          type="primary"
          disabled
          custom-class="h-30 linh-30 br-30 px-24"
          :custom-style="{ minWidth: '200rpx' }"
        />
      </template>
    </template>
    <!-- 活动开始 -->
    <template v-else-if="item.activityStatus === ActivityStatusEnum.START">
      <TButton
        v-if="item.register?.approvalStatus === ApprovalStatusEnum.NOTPASS"
        text="未通过"
        type="primary"
        disabled
        custom-class="h-30 linh-30 br-30 px-24"
        :custom-style="{ minWidth: '200rpx' }"
      />

      <TButton
        v-else
        text="活动进行中"
        type="primary"
        disabled
        custom-class="h-30 linh-30 br-30 px-24"
        :custom-style="{ minWidth: '200rpx', background: '#E29942', color: '#fff' }"
      />
    </template>
    <!-- 活动结束 -->
    <TButton
      v-else-if="item.activityStatus === ActivityStatusEnum.END"
      text="已结束"
      type="primary"
      disabled
      custom-class="h-30 linh-30 br-30 px-24"
      :custom-style="{ minWidth: '200rpx' }"
    />
    <TButton
      v-else-if="item.activityStatus === ActivityStatusEnum.CANCEL"
      text="活动已取消"
      type="primary"
      disabled
      custom-class="h-30 linh-30 br-30 px-24"
      :custom-style="{ minWidth: '200rpx' }"
    />
    <TButton
      v-else-if="item.activityStatus === ActivityStatusEnum.UNDERREVIEW"
      text="活动审核中"
      type="primary"
      disabled
      custom-class="h-30 linh-30 br-30 px-24"
      :custom-style="{ minWidth: '200rpx' }"
    />
    <TButton
      v-else-if="item.activityStatus === ActivityStatusEnum.AUDITFAILURE"
      text="活动审核失败"
      type="primary"
      disabled
      custom-class="h-30 linh-30 br-30 px-24"
      :custom-style="{ minWidth: '200rpx' }"
    />
  </view>
</template>

<script setup lang="ts">
  import { type PropType, computed } from 'vue';
  import { type IActivityListResData } from '@/api/activity/types';
  import { ActivityStatusEnum, ApprovalStatusEnum } from '@/enums/activityStatusEnum';
  import { Toast } from '@/utils';
  import TButtonGroup from '@/components/TButtonGroup/index.vue';
  import TButton from '../TButtonGroup/TButton.vue';
  import { useUserStoreWithOut } from '@/store/modules/user';
  import { useAdminStoreWithOut } from '@/store/modules/admin';
  import { navigateTo } from '@/router';
  import { storeToRefs } from 'pinia';
  import { isLogin } from '@/utils/is';
  import { toSelectiveType } from '@/utils/dynamicConfig';

  const useUser = useUserStoreWithOut();
  const { currentCocId, userInfo } = storeToRefs(useUser);

  const emit = defineEmits(['afterFnc', 'refresh']);

  const props = defineProps({
    importType: {
      type: String as PropType<'list' | 'details'>,
      default: 'list',
    },
    item: {
      type: Object as PropType<IActivityListResData>,
      required: true,
    },
  });

  const getMemberSignUpText = computed(() => {
    const { register } = props.item;
    switch (register?.approvalStatus) {
      case null:
      case undefined:
      case ApprovalStatusEnum.REJECT:
        return '';
      case ApprovalStatusEnum.UNDERREVIEW:
        return '审核中';
      case ApprovalStatusEnum.NOTPASS:
        return '未通过';
      case ApprovalStatusEnum.PASSED:
        return '已通过';
    }
  });

  /** 会员报名 */
  function memberSignUp() {
    const { id } = props.item;
    navigateTo({
      name: 'signUpInfoConfirm',
      options: {
        activityId: id,
        registerType: 'mini',
        success: () => emit('afterFnc'),
      },
    });
  }

  function isNumMax(maxNum?: number, passedNum?: number) {
    if (!maxNum || !passedNum) return false;
    return maxNum - passedNum <= 0;
  }

  /** 非会员报名 */
  function nonmemberSignUp() {
    const { id, memberOpen } = props.item;
    if (currentCocId || memberOpen) {
      navigateTo({
        name: 'signUpInfoConfirm',
        options: {
          activityId: id,
          registerType: 'mini',
          success: () => {
            emit('afterFnc');
          },
        },
      });
      return;
    }
    Toast({
      title: '此活动仅向会员开放,您无报名权限',
    });
  }

  function toSignUp(type: 'member' | 'nonmember' | 'gmatPage') {
    if (userInfo.value.phonenumber) {
      if (isDetails()) {
        const { memberOpen, id, passedNum, maxNum, enrollRestrict } = props.item;
        // if (type === 'gmatPage') {
        //   navigateTo({
        //     name: 'gmatPage',
        //     options: {
        //       activityId: id,
        //       memberOpen,
        //       callback: () => emit('afterFnc'),
        //     },
        //   });
        //   return;
        // }
        if (!currentCocId.value && !memberOpen) {
          uni.showModal({
            title: '提示',
            content: '此活动仅向会员开放,您无报名权限',
            showCancel: false,
            confirmText: '立即入会',
            success: () => {
              toSelectiveType(
                {
                  linkUrl: 'selectiveType',
                  isRedirectTo: true,
                },
                () => {},
                true,
              );
            },
          });
          return;
        }
        if (enrollRestrict && isNumMax(maxNum, passedNum)) {
          return Toast({ title: '报名人数已满，请联系主办方', success: () => emit('afterFnc') });
        }
        type === 'member' ? memberSignUp() : nonmemberSignUp();
        // Toast('您暂未加入任何单位，请联系本单位管理员')
        /** 根据产品需求 去掉报名时 验证完善资料验证 */
        // useUser.validatePerfectionInfo().then(() => {});
      } else {
        emit('afterFnc');
      }
    } else {
      isLogin(() => emit('refresh'));
    }
  }

  /** 是否是活动详情 */
  function isDetails() {
    return props.importType === 'details';
  }

  /**
   * 跳转直播
   */
  function gotoLive() {
    let finderUserName = props.item.tripartiteId;
    wx.getChannelsLiveInfo({
      finderUserName,
      success: ({ feedId, nonceId }) => {
        try {
          wx.openChannelsLive({
            finderUserName,
            feedId,
            nonceId,
          });
        } catch (error) {
          Toast('直播未开始', 'error');
        }
      },
      fail: (err: any) => {
        if (err.err_code === 100008) {
          Toast('小程序与视频号主体信息不一致');
        } else {
          Toast('直播调用失败', 'error');
        }
      },
    });
  }

  /**
   * 预约直播
   */
  function subscribe() {
    let finderUserName = props.item.tripartiteId;
    (wx as any).getChannelsLiveNoticeInfo({
      finderUserName,
      success: async ({ status, noticeId, reservable }: any) => {
        if (!noticeId) return;
        switch (status) {
          case 0:
            reservable ? (wx as any).reserveChannelsLive({ noticeId }) : Toast('无法预约');
            break;
          case 1:
            Toast('预约已取消', 'error');
            break;
          case 2:
            Toast('已预约');
            break;
        }
      },
      fail: (err: { err_code: number; errMsg: string }) => {
        if (err.err_code === 100008) {
          Toast('小程序与视频号主体信息不一致');
        } else {
          Toast('无可预约直播', 'error');
        }
      },
    });
  }
</script>

<style lang="scss" scoped>
  .form-title {
    padding: 30rpx 0;
    text-align: center;
    font-size: 31rpx;
    color: #333;
    word-break: break-all;
  }

  .form-container {
    margin: 0 30rpx;
    .form-button-group {
      display: flex;
      align-items: center;
      border-top: 2rpx solid #dddddd;
      position: relative;
      &::after {
        content: '';
        position: absolute;
        left: 50%;
        top: 0;
        height: 100%;
        width: 2rpx;
        background-color: #dddddd;
      }

      .btn {
        flex: 1;
        font-size: 27rpx;
        color: #1c59ff;
        height: 92rpx;
        line-height: 92rpx;
      }
    }
  }
</style>
